package com.myKng.search.service;

import lombok.extern.slf4j.Slf4j;
import org.apache.tika.exception.TikaException;
import org.apache.tika.metadata.Metadata;
import org.apache.tika.parser.AutoDetectParser;
import org.apache.tika.parser.ParseContext;
import org.apache.tika.parser.Parser;
import org.apache.tika.sax.BodyContentHandler;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.xml.sax.SAXException;

import java.io.IOException;
import java.io.InputStream;
import java.util.Arrays;
import java.util.List;

@Slf4j
@Service
public class DocumentParserService {

    @Value("${document.parsing.max-size}")
    private String maxSize;

    @Value("${document.parsing.supported-types}")
    private String supportedTypes;

    /**
     * 解析文档内容
     *
     * @param inputStream 文档输入流
     * @param fileName    文件名
     * @param contentType 内容类型
     * @return 解析后的文本内容
     */
    public String parseDocument(InputStream inputStream, String fileName, String contentType) {
        try {
            // 检查文件类型是否支持
            if (!isSupportedContentType(contentType)) {
                log.warn("不支持的文件类型: {}", contentType);
                return "";
            }

            // 使用Tika解析文档
            Parser parser = new AutoDetectParser();
            BodyContentHandler handler = new BodyContentHandler(-1); // -1表示不限制文本长度
            Metadata metadata = new Metadata();
            metadata.set(Metadata.RESOURCE_NAME_KEY, fileName);
            metadata.set(Metadata.CONTENT_TYPE, contentType);

            ParseContext context = new ParseContext();
            parser.parse(inputStream, handler, metadata, context);
            
            String content = handler.toString();
            log.debug("成功解析文档: {}, 内容长度: {}", fileName, content.length());
            return content;
            
        } catch (IOException e) {
            log.error("解析文档IO异常: {}", fileName, e);
        } catch (SAXException e) {
            log.error("解析文档SAX异常: {}", fileName, e);
        } catch (TikaException e) {
            log.error("Tika解析异常: {}", fileName, e);
        } catch (Exception e) {
            log.error("解析文档未知异常: {}", fileName, e);
        }
        return "";
    }
    
    /**
     * 检查文件类型是否支持
     *
     * @param contentType 内容类型
     * @return 是否支持
     */
    private boolean isSupportedContentType(String contentType) {
        if (contentType == null || contentType.isEmpty()) {
            return false;
        }
        
        List<String> supportedTypesList = Arrays.asList(supportedTypes.split(","));
        return supportedTypesList.contains(contentType) || 
               contentType.startsWith("text/") || 
               contentType.startsWith("application/pdf") || 
               contentType.startsWith("application/msword") || 
               contentType.startsWith("application/vnd.openxmlformats-officedocument");
    }